package com.newa.actions;

import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.newa.beans.Section;
import com.newa.beans.Work;
import com.newa.dao.DAOSection;
import com.newa.dao.DAOWorks;
import com.newa.utils.HibUtil;
import com.opensymphony.xwork2.ActionSupport;

public class onework extends ActionSupport {
	private Logger LOG = Logger.getLogger(addWork.class);
	private int id;
	private Work work;
	private ArrayList<Section> sections;
	private int max;
	private int min = Integer.MAX_VALUE;
	private int prev;
	private int next;

	@Override
	public String execute() throws Exception {
		if (id < 1) {
			return "error";
		}
		Session session = HibUtil.getSessionFactory().openSession();
		Session session1 = HibUtil.getSessionFactory().openSession();
		DAOWorks daow = new DAOWorks(session);
		DAOSection daos = new DAOSection(session1);
		ArrayList<Work> wrk = daow.getAllWorks();
		if(prev!=0){
			setId(prev);
		}
		if(next!=0){
			setId(next);
		}
		for (int i = 0; i < wrk.size(); i++) {
			setMax(Math.max(wrk.get(i).getID(), max));
			setMin(Math.min(wrk.get(i).getID(), min));
			if (wrk.get(i).getID() == id) {
				if (i > 0) {
					prev = wrk.get(i - 1).getID();
				}
				if (i < wrk.size()-1) {
					next = wrk.get(i + 1).getID();
				}
			}
		}
		try {
			setWork(daow.getWorkById(id));
			if (work == null) {
				return "error";
			}
			setSections(daos.getAllSections());
		} catch (Exception e) {
			LOG.warn(e);
			throw new RuntimeException(e);
		} finally {
			daow.closeSession().close();
			daos.closeSession().close();
		}
		return "success";
	}

	public int getPrev() {
		return prev;
	}

	public void setPrev(int prev) {
		this.prev = prev;
	}

	public int getNext() {
		return next;
	}

	public void setNext(int next) {
		this.next = next;
	}

	public int getMax() {
		return max;
	}

	public int getMin() {
		return min;
	}

	public void setMin(int min) {
		this.min = min;
	}

	public void setMax(int max) {
		this.max = max;
	}

	public ArrayList<Section> getSections() {
		return sections;
	}

	public void setSections(ArrayList<Section> sections) {
		this.sections = sections;
	}

	public Work getWork() {
		return work;
	}

	public void setWork(Work work) {
		this.work = work;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}
